#include<getopt.h>
#include<time.h>

#include"main.h"
#include"mac.h"

FILE *fp;

//时间戳
struct time_val
{
    int tv_sec;         //时间戳高位
    int tv_usec;        //时间戳低位
};
 
//pcap数据包头结构体
struct pcap_pkthdr
{
    struct time_val ts; // time stamp 
    u_int32 caplen;     // 当前数据帧的长度
    u_int32 len;        //离线数据的长度
};

int main(int argc,char *argv[]){

    //参数处理
    char filename[100];
    int target;
    int opt=0;
    while((opt=getopt(argc,argv,"f:i:"))!=-1){
        switch (opt){
            case 'f':strcpy(filename,optarg);break;
            case 'i':target=atoi(optarg);break;
        }
    }

    int index=0;
    struct pcap_pkthdr *ptk_header;
    int  pkt_offset = 0;

    //打开pcap文件
    if ((fp = fopen(filename, "r")) == NULL){
        printf("error: can not open pcap file\n");
        exit(0);
    }

    ptk_header = (struct pcap_pkthdr *)malloc(sizeof(struct pcap_pkthdr));

    pkt_offset = 24; //pcap文件头结构 24个字节,直接忽略
    
    //遍历数据包
    while (fseek(fp, pkt_offset, SEEK_SET) == 0){ 
        //处理pcap包头结构
        memset(ptk_header, 0, sizeof(struct pcap_pkthdr));
        if (fread(ptk_header, 16, 1, fp) != 1) { 
            printf("\nread end of pcap file\n");
            break;
        }
        pkt_offset += 16 + ptk_header->caplen;   //下一个数据包的偏移值

        index++;
        if(index == target){
            printf("****************************************************************\n");
            process_mac(fp);   
        }
        if(index>target){
            break;
        }
    }
}